﻿using System;
using System.Collections.Specialized;
using System.Web;

namespace UrlRouting
{
    public class HttpModule : IHttpModule
    {
        private static RouterEngine routerEngine = new RouterEngine(
            new IsapiDomain[] { 
                    //new IsapiDomain { CID = 1271, Name = "accutherm", VD = "assets/1"}, 
                    //new IsapiDomain { CID = 2322, Name = "hylokusa", VD = "assets/1"}, 
                    //new IsapiDomain { CID = 1002, Name = "orientalmotor", VD = "assets/1"},
                    //new IsapiDomain { CID = 9655, Name = "catnavqa", VD = "assets/u"},
                    new IsapiDomain { CID = 48450, Name = "cbplp-Timken", VD = "assets/u", Legacy = true},
                    new IsapiDomain { CID = 96720, Name = "cbplp-demo", VD = "assets/u", Legacy = false},
                });

        public void Dispose() { }

        public void Init(HttpApplication httpApplication)
        {
            httpApplication.BeginRequest += BeginRequest;
        }

        private void BeginRequest(object sender, EventArgs args)
        {
            HttpContext httpContext = ((HttpApplication)sender).Context;
            string path;
            NameValueCollection headers;
            if (routerEngine.Process(httpContext.Request.Url, out path, out headers))
            {
                httpContext.RewritePath(path, true);
                httpContext.Request.Headers.Add(headers);
            }
        }
    }
}
